<template>

<div class="demo-form-top">
  <div class="demo-input-size">
    <label style="margin-right: 10px;">品牌名称 </label>
  <el-input
      style="width: 200px"
      v-model="input1"
      class="w-50 m-2"
      size="large"
      placeholder="请输入品牌名搜索"
      :suffix-icon="Search"
  />
  </div>
  <div class="demo-button-size">
     <el-button type="primary" @click="getBrandList">搜索</el-button>
  </div>
  <div class="demo-button-size">
    <el-button type="success" @click="addOpen">新增</el-button>
  </div>
  <div class="demo-button-size">
    <el-popconfirm title="这是确定批量删除吗？" @confirm="delHandle(null)">
      <template #reference>
        <el-button type="danger"  :disabled="delBtlStatu">批量删除</el-button>
      </template>
    </el-popconfirm>
  </div>
</div>


  <div class="demo-table-size">
    <el-table
        ref="multipleTableRef"
        :data="tableData"
        style="width: 100%"
        tooltip-effect="dark"
        stripe
        border
        @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"  />
      <el-table-column property="name" label="品牌名" width="120" align="center" />
      <el-table-column property="logoImg" label="品牌logo" align="center">
        <template #default="scope">
          <el-image
              style="width: 100px; height: 100px"
              :src="baseUrl+scope.row.logoImg"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :initial-index="4"
              fit="cover"
          />
        </template>
      </el-table-column>
      <el-table-column property="blurb" label="品牌简介" align="center" show-overflow-tooltip />
      <el-table-column property="icon"  align="center" width="200" label="操作">
        <template #default="scope">
          <el-button type="primary"  @click="editHandle(scope.row.id)" >编辑</el-button>
          <el-divider direction="vertical"></el-divider>
          <el-popconfirm title="这是一段内容确定删除吗？" @click="delHandle(scope.row.id)"   @confirm="">
            <template #reference>
            <el-button type="danger"  >删除</el-button>
            </template>
          </el-popconfirm>

        </template>
      </el-table-column>

    </el-table>
    <div style="margin-top: 15px;">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          style="float: right;margin-right: 30px"
          small
          background
          :page-sizes="[5, 10, 20, 30]"
          v-model:total="pageParam.total"
          layout="total, sizes, prev, pager, next"
          class="mt-4"
          v-model:current-page="pageParam.current"
          v-model:page-size="pageParam.size"
         />


  </div>
  </div>

  <!--新增对话框-->
  <el-dialog
      :title="dialogName"
      v-model="dialogVisible"
      width="600px"
      :before-close="handleClose">

    <el-form
        ref="ruleFormRef"
        :rules="rules"
        :model="editForm"  >
      <el-form-item prop="id" >
        <el-input type="hidden" v-model="editForm.id" ></el-input>
      </el-form-item>

      <el-form-item label="品牌名称" prop="name" label-width="100px">
        <el-input  v-model="editForm.name" ></el-input>
      </el-form-item>

      <el-form-item label="品牌logo"  prop="logoImg" label-width="100px">
        <UploadUtil  v-model="editForm.logoImg" :message="parentMessage"  @childEvent="handleChildEvent" />
      </el-form-item>
      <el-form-item label="品牌简介"  prop="blurb" label-width="100px">
        <el-input  v-model="editForm.blurb"  :autosize="{ minRows: 5, maxRows: 15}"  type="textarea"  autocomplete="off"></el-input>
      </el-form-item>



    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="resetForm(ruleFormRef)">取 消</el-button>
      <el-button type="primary" @click="submitForm(ruleFormRef)">确 定</el-button>
    </div>
  </el-dialog>



</template>
<script setup>


import {Search} from "@element-plus/icons-vue";
import {inject, nextTick, onMounted, reactive, ref} from "vue";
import UploadUtil from "@/components/UploadUtil.vue";
import { ElMessage } from 'element-plus';
import axios from "@/axios.js"

const baseUrl = '../../public/img/'



const input1 = ref('')

onMounted(()=>{
  getBrandList()
})

const pageParam = ref({
    current:1,
    total:10,
    size:5
})

//分页查询
const getBrandList = ()=>{
    axios.get(`/brand/list`,{
      params: {
        name: input1.value,
        current: pageParam.value.current,
        size: pageParam.value.size
      }
    }).then(res=>{
        tableData.value = res.data.records
        pageParam.value.current = res.data.current
        pageParam.value.total= res.data.total
        pageParam.value.size = res.data.size
    })
}

const handleSizeChange = (val)=>{
  console.log(`每页 ${val} 条`)
  pageParam.value.size = val
  getBrandList()
}
const handleCurrentChange = (val)=>{
  console.log(`当前页: ${val}`)
  pageParam.value.current = val
  getBrandList()
}


const multipleTableRef = ref()
const multipleSelection = ref([])
const handleSelectionChange = (val) => {
  console.log("勾选")
  console.log(val)
  multipleSelection.value = val
  delBtlStatu.value = val.length==0
}
const toggleSelection = (rows) => {
  if (rows) {
    rows.forEach(row => {
      multipleTableRef.value.toggleRowSelection(row)
    });
  } else {
      multipleTableRef.value.clearSelection();
  }
}

const delBtlStatu = ref(true)

//删除/批量删除
const delHandle = (id) => {

  var ids = []
  if (id) {
    ids.push(id)
  } else {
    multipleSelection.value.forEach(row => {
      ids.push(row.id)
    })
  }
  console.log(ids)

  axios.post("/brand/delete", ids).then(res => {
    ElMessage({
      showClose: true,
      message: '恭喜你，删除成功',
      type: 'success',
      onClose: () => {
        getBrandList(); // 在消息关闭时调用getBrandList方法
      }
    });
  })
}


const tableData = ref(
    [
      {
        id:1,
        name: 'Tom',
        logoImg:"",
        blurb: 'No. 189, Grove St, Los Angeles',

      }
    ]
)

//图片上传部分
const handleChildEvent = (data) => {
  console.log('Received from child: ' + data);
  parentMessage.value = data
  editForm.value.logoImg = parentMessage
};
const parentMessage = ref('');



//新增/编辑
const dialogVisible = ref(false)
const handleClose = ()=>{
    dialogVisible.value = false
    parentMessage.value= ""
    editForm.value = ref({})
}
const editForm = ref({


})


const ruleFormRef = ref(null)
const rules = reactive({
  name: [
    { required: true, message: '不能为空', trigger: 'blur' },
  ],
  logoImg: [
    {
      required: true, message: 'logo不能为空', trigger: 'change'},
  ],
})
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log(editForm.value)
      axios.post('/brand/' + (editForm.value.id?'update':'save'), editForm.value)
          .then(res => {

            ElMessage({
              showClose: true,
              message: '恭喜你，操作成功',
              type: 'success',
              onClose: () => {
                getBrandList(); // 在消息关闭时调用getBrandList方法

              }
            });
            resetForm(formEl)

          })
    } else {
      console.log('error submit!', fields)
    }
  })
}

const editHandle = (id) => {

    axios.get('/brand/info/' + id).then(res => {
      editOpen()
      nextTick(() => {
        editForm.value = res.data
        parentMessage.value = editForm.value.logoImg
      })

  })
}

const resetForm = (formEl) => {
  if (!formEl) return
  dialogVisible.value = false
  parentMessage.value = ""
  formEl.resetFields()
}

const dialogName = ref("")

const addOpen = ()=>{
  dialogName.value = "新增"
  dialogVisible.value = true

}
const editOpen = ()=>{
  dialogName.value = "编辑"
  dialogVisible.value = true
}



</script>


<style scoped>
.demo-form-top{

}

.demo-button-size{
  float: left;
  display: flex;
  align-items: center;
  margin-top: 5px;
  margin-left: 7px;
}

.demo-input-size{
  float: left;
  width: 300px;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.demo-table-size{

  margin-top: 20px;
}

.dialog-footer{
  margin-left: 100px;
}


</style>
<style>
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
.el-table__header thead th {
  background-color: #F5F7FA!important;
}

</style>